import {useStore} from "vuex";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";
import {confirm} from "@/utils/utils.js";
import {useRouter} from "vue-router";

export function useProductApi() {
    const store = useStore()
    const router = useRouter()

    const addCart = async (id) => {
        await request.post('/cart', {
            productId: id,
            count: 1
        })
        await store.dispatch('getCartCount')
        ElMessage.success('添加到购物车成功!')
    }

    const createOrder = async (row) => {
        confirm(`是否确认创建[${row.name}]订单?`, async () => {
            await request.post('/order/create', [{
                productId: row.id,
                count: 1
            }])
            ElMessage.success('创建成功')
        })
    }

    const handleProductClick = async (id) => {
        await router.push(`/userHome/productDetail?id=${id}`)
    };

    return {
        addCart,
        createOrder,
        handleProductClick
    };
}